package com.star.starojcodesandbox.job;


import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.ListContainersCmd;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.core.DockerClientBuilder;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class CleanContainer {

    @Scheduled(cron = "0 0 17 * * ?")
    public void ExitContainer() {
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        ListContainersCmd listContainersCmd = dockerClient.listContainersCmd();
        List<Container> containers = listContainersCmd.withShowAll(true).exec();

        List<String> ids = containers.stream().filter(item -> item.getStatus().startsWith("Exited") && item.getImage().equals("openjdk:8-alpine"))
                .map(Container::getId).collect(Collectors.toList());
        for (String id : ids) {
            dockerClient.removeContainerCmd(id).exec();
        }

    }

    @Scheduled(cron = "0 0 23 * * ?")
    public void RunExitContainer() {
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        ListContainersCmd listContainersCmd = dockerClient.listContainersCmd();
        List<Container> containers = listContainersCmd.withShowAll(true).exec();

        List<String> ids = containers.stream().filter(item -> item.getStatus().startsWith("Up") && item.getImage().equals("openjdk:8-alpine"))
                .map(Container::getId).collect(Collectors.toList());
        for (String id : ids) {
            dockerClient.stopContainerCmd(id).exec();
        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (String id : ids) {
            dockerClient.removeContainerCmd(id).exec();
        }

    }
}

